<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="/images/icons/home_icon.ico">
    <link rel="stylesheet" href="/css/pagecss/img.css">
    <link rel="stylesheet" href="/css/normalize.css_v8.0.1.css">
    <script src="/js/jq1.11.3.min.js"></script>
    <script src="/js/jqajax.js"></script>
    <title>img</title>
</head>

<body>
    <div id="container"></div>
    <div id="preview" style="display:none;"></div>
    <div id="params">
        <form>
            <span>【图片类型】</span>
            <label><input type="radio" name="type" value="jpg" checked><span>jpg</span></label>
            <label><input type="radio" name="type" value="gif"><span>gif</span></label>
            <label><input type="radio" name="type" value="png"><span>png</span></label>
            <span>【图片来源】</span>
            <label><input type="radio" name="source" value="local" checked><span>本地</span></label>
            <label><input type="radio" name="source" value="network"><span>网络</span></label>
            <span>【加载方式】</span>
            <label><input type="radio" name="ran" value="1" checked><span>随机</span></label>
            <label><input type="radio" name="ran" value="0"><span>分页</span></label>
            <button type="button" id="submitLoad">加载</button>
        </form>
    </div>
    <script type="text/javascript">
        const cols = 4 // 列数
        const spacing = 5 // div 间距
        const W = $('#container').innerWidth()
        const bodyH = $(document).height()
        const itemW = W / cols - spacing * 2 // div 宽度
        let params = {
            ran: 1,
            page: 1,
            num: 50,
            type: 'jpg',
            source: ''
        }
        let idIndex = 1
        let onRepeat;
        let loadEnd = false;
        let heightList;
        $('#submitLoad').on('click', function () {
            let formdata = $('form').serializeArray()
            for (let item of formdata) {
                params[item.name] = item.value
            }
            $('#container').empty()
            initData()
        })
        // 初始加载数据
        function initData() {
            onRepeat = false
            params.page = 1
            heightList = new Array(cols);
            heightList.fill(0);
            getList()
        }
        initData()
        // 生成全局唯一标识符 guid
        function guid(head = '') {
            const S = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            return `${head}${S()}${S()}-${S()}-${S()}-${S()}-${S()}${S()}${S()}`;
        }
        // 获取图片列表
        function getList() {
            if (onRepeat) return
            onRepeat = true
            console.log('-->>> 加载更多')
            if (params.source == 'network') {
                apiGet('/api/mockdata?name=imgListjson').then(res => {
                    if (res.code) return
                    if (!res[params.type + 'List']) return
                    let resImgList = res[params.type + 'List'].map(item => {
                        return { url: item, id: guid('img') }
                    })
                    renderImg(resImgList, () => {
                        onRepeat = false
                        loadEnd = true
                    })
                })
                return
            }
            apiGet('/api/fileAll', params).then(res => {
                if (res.code !== 0) return
                let resImgList = res.data.map(item => {
                    return { url: item.url, id: guid('img') }
                })
                renderImg(resImgList, () => {
                    console.log(heightList, '-->>> 678')
                    params.page++
                    onRepeat = false
                    // 如果未撑满屏幕则继续加载更多
                    if (Math.max(...heightList) < bodyH * 1.2) {
                        getList()
                    }
                })
            })
        }
        // 渲染图片
        function renderImg(list, done) {
            let count = list.length
            for (let item of list) {
                let div = $(`<div style="width:${itemW}px;"><img src="${item.url}" data-id="${item.id}"></div>`)
                $('#container').append(div)
                let img = div.find('img')
                // 渲染完成在设置div的位置
                img.on('load', function () {
                    let colIndex = getMinIndex(heightList);
                    div.css({
                        top: heightList[colIndex] + spacing + "px",
                        left: (colIndex + 1) * spacing + colIndex * itemW + "px"
                    })
                    heightList[colIndex] += div[0].offsetHeight + spacing;
                    div.css('opacity', '1')
                    count--
                    if (count == 0 && typeof done === "function") {
                        done() // 加载完的回调
                    }
                })
                img.on('click', function () {
                    console.log(this.src, '-->>> 678')
                    let preImg = $(`<img data-id="${this.dataset.id}" src="${this.src}">`)
                    // 防止点击冒泡
                    preImg.on('click', function (event) {
                        event.stopPropagation();
                    })
                    $('#preview').append(preImg).show()
                    stopMove()
                })
            }
        }
        // 图片预览操作
        $('#preview').on('click', function () {
            $(this).empty().hide()
            canMove()
        })
        // 键盘左右键 切换
        window.addEventListener('keydown', function (e) {
            let key = e.key
            let currentId = $('#preview img').attr('data-id')
            if (key == 'ArrowLeft' || key == 'a') {
                var nextDom = $(`#container img[data-id=${currentId}]`).parent().prev().find('img')
                if (!nextDom.length) return console.log('-->>> 第一张了');
                setPreviewImgSrc(nextDom)
            }
            if (key == 'ArrowRight' || key == 'd') {
                var nextDom = $(`#container img[data-id=${currentId}]`).parent().next().find('img')
                if (!nextDom.length) return console.log('-->>> 最后一张了');
                setPreviewImgSrc(nextDom)
            }
        })
        // 设置预览图片 src
        function setPreviewImgSrc(nextDom) {
            $('#preview img').attr({
                src: nextDom.attr('src'),
                'data-id': nextDom.attr('data-id')
            })
        }
        // 获取数组元素最小值的下标
        function getMinIndex(array) {
            return array.indexOf(Math.min(...array))
        }
        // 页面渲染完成，开始进行瀑布流布局
        window.onload = function () {
            watchScroll()
        }
        // 监听scroll事件下拉加载更多
        function watchScroll() {
            var flag = false
            window.addEventListener('scroll', function () {
                if (flag) return
                if (loadEnd) return
                flag = true
                let contentH = Math.min(...heightList)
                let scrollTop = document.body.scrollTop || document.documentElement.scrollTop
                if (scrollTop > contentH - window.screen.availHeight) {
                    getList()
                }
                setTimeout(() => { flag = false }, 50)
            }, false)
        }
        // 停止页面滚动[pc端]
        function stopMove() {
            document.body.style.overflow = 'hidden'
            document.addEventListener('touchmove', function (e) {
                e.preventDefault()
            }, { passive: false })
        }
        // 开启页面滚动[pc端]
        function canMove() {
            document.body.style.overflow = ''
            document.removeEventListener('touchmove', function (e) {
                e.preventDefault()
            }, { passive: true })
        }
    </script>
</body>

</html>